package com.tieshan.smartwindow.other

import android.content.Context
import com.tieshan.smartwindow.app.AppApplication
import timber.log.Timber
import java.io.*
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

/**
 *   author : Hleo
 *   time   : 2022/2/23
 *   desc   : 文件处理类
 */
object FileUtil {
    /**
     * 删除文件夹
     * @param folderPath 文件夹完整绝对路径 ,"Z:/xuyun/save"
     */
    fun delFolder(folderPath: String) {
        try {
            delAllFile(folderPath) //删除完里面所有内容
            var filePath = folderPath
            filePath = filePath
            val myFilePath = File(filePath)
            myFilePath.delete() //删除空文件夹
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 删除指定文件夹下所有文件
     * @param path 文件夹完整绝对路径 ,"Z:/xuyun/save"
     */
    fun delAllFile(path: String): Boolean {
        var flag = false
        val file = File(path)
        if (!file.exists()) {
            return flag
        }
        if (!file.isDirectory()) {
            return flag
        }
        if (file.list() != null && file.list().size != 0) {
            val tempList: Array<String> = file.list()
            var temp: File? = null
            for (i in tempList.indices) {
                if (path.endsWith(File.separator)) {
                    temp = File(path + tempList[i])
                } else {
                    temp = File(path + File.separator + tempList[i])
                }
                if (temp.isFile()) {
                    temp.delete()
                }
                if (temp.isDirectory()) {
                    delAllFile(path + "/" + tempList[i]) //先删除文件夹里面的文件
                    delFolder(path + "/" + tempList[i]) //再删除空文件夹
                    flag = true
                }
            }
        }
        return flag
    }

    /**
     * 删除文件下的指定文件
     * @param path 文件夹完整绝对路径 ,"Z:/xuyun/save"
     */
    fun delAllFile(path: String, files: ArrayList<File>) {
        val file = File(path)
        if (!file.exists()) {
            return
        }
        if (!file.isDirectory()) {
            return
        }
        for (i in files.indices) {
            if (files[i].isFile && files[i].exists())
                files[i].delete()
        }
    }


    /**
     *
     * 获取dataFile文件夹下的所有文件
     *
     */
    fun getAllDataFileName(file: File): ArrayList<File>? {
// 文件夹路径
        val fileList: ArrayList<File> = ArrayList<File>()
        val tempList = file.listFiles()
        if (tempList != null && tempList.size != 0) {
            for (index in 0..tempList.size - 1) {
                fileList.add(tempList[index])
            }
        }
        return fileList
    }

    /**
     * 读取文件
     */
    /**
     * 读文件
     * @param name
     * @return
     */
    fun readFile(file: String?, log: String?): String? {
        var content = ""
        try {
            val instream: InputStream = FileInputStream(file)
            if (instream != null) {
                val inputreader = InputStreamReader(instream)
                val buffreader = BufferedReader(inputreader)
                var line: String? = null
                //分行读取
                while (run {
                        line = buffreader.readLine()
                        line
                    } != null) {
                    content += line + "\n"
                }
                instream.close()
                val logs = log + "\n" + content;
                val fileWriter = FileWriter(file)
                val bufferedWriter = BufferedWriter(fileWriter)
                bufferedWriter.write(logs)
                bufferedWriter.flush()
                bufferedWriter.close()

            }
        } catch (e: Exception) {
            Timber.d("文件报错=${e.message!!}")
        }
        return content;
    }

    /**
     * 写文件
     */

    fun writeFile(path: String, startfilename: String, content: String, read: Boolean) {
        try {
            /**
             * 创建文件夹
             */
            val folder = File(path)
            if (!folder.exists())
                folder.mkdirs()
            //高位不够自动补零
            val decimalFormat = DecimalFormat("00")
            val calendar = Calendar.getInstance()
            val fileName = "${decimalFormat.format(calendar[Calendar.YEAR].toLong())}-${
                decimalFormat.format((calendar[Calendar.MONTH] + 1).toLong())
            }-${
                decimalFormat.format(
                    calendar[Calendar.DAY_OF_MONTH].toLong()
                )
            }"
            val logname = "$startfilename-${fileName}.log"

            /**
             * 创建日志文件
             */
            val file = File(folder.absolutePath + File.separator + logname)
            if (!file.exists()) {
                try {
                    file.createNewFile()
                } catch (e: IOException) {
                    file.delete()
                    file.createNewFile()
                    Timber.d("Exception=${e}")
                }
                val fileWriter = FileWriter(file)
                val bufferedWriter = BufferedWriter(fileWriter)
                bufferedWriter.write(content)
                bufferedWriter.flush()
                bufferedWriter.close()
            } else {
                if (read)
                    readFile(file.path, content)
            }
        } catch (e: Exception) {

        }
    }

    /**
     * 写文件
     */

    fun writeFile(path: String, startfilename: String, content: String) {
        try {
            /**
             * 创建文件夹
             */
            val folder = File(path)
            if (!folder.exists())
                folder.mkdirs()
            val logname = "$startfilename.log"

            /**
             * 创建日志文件
             */
            val file = File(folder.absolutePath + File.separator + logname)
            if (!file.exists()) {
                try {
                    file.createNewFile()
                } catch (e: IOException) {
                    file.delete()
                    file.createNewFile()
                }
            } else {
                file.delete()
                file.createNewFile()
            }
            val fileWriter = FileWriter(file)
            val bufferedWriter = BufferedWriter(fileWriter)
            bufferedWriter.write(content)
            bufferedWriter.flush()
            bufferedWriter.close()
        } catch (e: Exception) {

        }
    }

    fun writeLog(fileName: String, message: String) {
        val path = AppApplication.app?.getExternalFilesDir("log")?.absolutePath?:return
        val logFile = File(path, fileName)
        val parentFile = File(path)
        try {
            if(parentFile.exists().not()){
                parentFile.mkdirs()
            }
            if(logFile.exists().not()){
                logFile.createNewFile()
            }

            FileWriter(logFile, true).use { writer ->
                writer.appendLine(message)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 写文件
     */

    fun writeLogFile(path: String, startfilename: String, content: String) {
        try {
            /**
             * 创建文件夹
             */
            val folder = File(path)
            if (!folder.exists())
                folder.mkdirs()
            val logname = "$startfilename.log"
            /**
             * 创建日志文件
             */
            val file = File(folder.absolutePath + File.separator + logname)
            if (!file.exists()) {
                try {
                    file.createNewFile()
                } catch (e: IOException) {
                    file.delete()
                    file.createNewFile()
                }
            }
            val fileWriter = FileWriter(file)
            val bufferedWriter = BufferedWriter(fileWriter)
            bufferedWriter.write(content)
            bufferedWriter.flush()
            bufferedWriter.close()
        } catch (e: Exception) {

        }
    }

}